package com.xctech.ipb.dpn.hyc.domain.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xctech.ipb.dpn.hyc.domain.entity.Station;
import com.xctech.ipb.dpn.hyc.infrastructure.mapper.StationMapper;
import com.xctech.ipb.dpn.hyc.model.req.StationInfoReq;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import static com.xctech.ipb.dpn.common.constant.DBConstants.DB_BATCH_SIZE;

@Slf4j
@Service
public class StationService extends ServiceImpl<StationMapper, Station> {

    public int syncStation(List<StationInfoReq> stationInfoReqList) {
        // 转为入库类
        List<Station> stationList = new ArrayList<>();
        for (StationInfoReq stationInfo : stationInfoReqList) {
            Station station = new Station();
            BeanUtils.copyProperties(stationInfo, station);
            stationList.add(station);
        }
        return insertOrUpdateBatch(stationList);
    }

    public int insertOrUpdateBatch(List<Station> list) {

        if (list == null || list.isEmpty()) {
            log.warn(" 同步站点信息为空, 跳过处理");
            return 0;
        }

        int totalCount = 0;
        int batchCount = 0;
        try {
            // 分批处理
            for (int i = 0; i < list.size(); i += DB_BATCH_SIZE) {
                int endIndex = Math.min(i + DB_BATCH_SIZE, list.size());
                List<Station> batch = list.subList(i, endIndex);

                // 执行批量插入或更新
                int affectedRows = baseMapper.insertOrUpdateBatch(batch);
                totalCount += batch.size();
                batchCount++;

                log.info("第{}站点处理完成，本批处理{}条记录，影响{}行，累计处理{}条记录",
                        batchCount, batch.size(), affectedRows, totalCount);
            }

            log.info("站点信息批量插入或更新完成，总共处理{}批，总记录数{}条", batchCount, totalCount);
            return totalCount;

        } catch (Exception e) {
            log.error("站点信息批量插入或更新失败，已处理{}条记录", totalCount, e);
            throw new RuntimeException("站点信息批量插入或更新失败", e);
        }
    }

}
